package com.jsgt.greekfire.ui.mine.coindetail

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.PriceFormatUtil
import com.fhx.core.utils.ToastUtils
import com.google.android.material.appbar.AppBarLayout
import com.jsgt.greekfire.*
import com.jsgt.greekfire.bean.AssetsBean
import com.jsgt.greekfire.event.AssetsEvent
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.ui.mine.coindetail.adapter.TradingRecordAdapter
import com.jsgt.greekfire.ui.mine.coindetail.receipt.ReceiptActivity
import com.jsgt.greekfire.ui.mine.coindetail.recharge.RechargeActivity
import com.jsgt.greekfire.ui.mine.coindetail.withdraw.WithdrawActivity
import com.jsgt.greekfire.ui.mine.coindetail.transfer.TransferActivity
import com.jsgt.greekfire.common.util.NetDataManager
import com.jsgt.greekfire.ui.mine.coindetail.gfctransfer.GFCTransferActivity
import com.jsgt.greekfire.viewmodel.UserViewModel
import com.scwang.smartrefresh.header.MaterialHeader
import kotlinx.android.synthetic.main.activity_coin_detail.*
import kotlinx.android.synthetic.main.view_coin_header.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal
import java.text.DecimalFormat
import kotlin.math.ceil

/**
 * 数字币详情
 * author fhx
 * create time 2020/4/24 17:28
 **/
class CoinDetailActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private lateinit var assetsBean: AssetsBean
    private var currentPage = 0//当前页码
    private var isRefresh = true
    private var price: Double = 1.0

    companion object {
        private const val ASSETS_BEAN = "bean"
        private const val PRICE = "price"
        fun start(context: Context, assetsBean: AssetsBean) {
            val intent = Intent(context, CoinDetailActivity::class.java)
            intent.putExtra(ASSETS_BEAN, assetsBean)
            context.startActivity(intent)
        }

        fun start(context: Context, assetsBean: AssetsBean, price: Double) {
            val intent = Intent(context, CoinDetailActivity::class.java)
            intent.putExtra(ASSETS_BEAN, assetsBean)
            intent.putExtra(PRICE, price)
            context.startActivity(intent)
        }
    }

    var sum = ""
    override fun onResume() {
        super.onResume()
        if (LOGIN_STATUS) {
            showProgress(true)
            updateView()
            NetDataManager.getUserAssets()
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_coin_detail

    override fun main() {
        refresh_layout.setEnableLoadMore(true)
        refresh_layout.setEnableRefresh(true)
        val materialHeader = MaterialHeader(this)
        materialHeader.setColorSchemeResources(R.color.black)
        refresh_layout.setRefreshHeader(materialHeader)
        refresh_layout.setOnRefreshListener {
            isRefresh = true
            when {
                record_all_rb.isChecked -> {
                    recordList("0")
                }
                record_transfer_rb.isChecked -> {
                    recordList("1")
                }
                else -> {
                    recordList("2")
                }
            }
        }
        refresh_layout.setOnLoadMoreListener {
            isRefresh = false
            when {
                record_all_rb.isChecked -> {
                    userViewModel.tradingRecord(
                        assetsBean.assetGuid!!,
                        "0",
                        currentPage + 1,
                        PAGE_SIZE
                    )
                }
                record_transfer_rb.isChecked -> {
                    userViewModel.tradingRecord(
                        assetsBean.assetGuid!!,
                        "1",
                        currentPage + 1,
                        PAGE_SIZE
                    )
                }
                else -> {
                    userViewModel.tradingRecord(
                        assetsBean.assetGuid!!,
                        "2",
                        currentPage + 1,
                        PAGE_SIZE
                    )
                }
            }
        }
        assetsBean = intent.getParcelableExtra(ASSETS_BEAN)
        price = intent.getDoubleExtra(PRICE, 1.0)


//        when (assetsBean.assetGuid) {
//            "1" -> {
//                icon_tv.setBackgroundResource(R.mipmap.icon_glb)
//            }
//            "2" -> {
//                icon_tv.setBackgroundResource(R.mipmap.icon_usdt)
//            }
//            "3" -> {
//                icon_tv.setBackgroundResource(R.mipmap.icon_gft)
//            }
////            "4" -> {
////                icon_tv.setBackgroundResource(R.mipmap.icon_ut)
////            }
//        }
        title = assetsBean.assetName.toString()

        block_chain_address_tv.text = assetsBean.transfer_address


        if (TextUtils.equals(assetsBean.assetName, "USDT")) {
            recharge_tv.visibility = View.VISIBLE
            withdraw_tv.visibility = View.VISIBLE
        } else {
            if (TextUtils.equals(assetsBean.assetName, "GFC")) {
                gfc_transfer.visibility = View.VISIBLE
            } else {
                withdraw_tv.visibility = View.VISIBLE
            }
            exchange_tv.visibility = View.VISIBLE
            exchange_tv.setOnClickListener {
                if (IS_ACTIVATION == 1) {
                    ToastUtils.show(
                        this@CoinDetailActivity,
                        getString(R.string.account_no_activation)
                    )
                } else {
                    ReceiptActivity.start(
                        this,
                        assetsBean
                    )
                }
            }
        }
        val childView = appBarLayout.getChildAt(0)
        val params = childView?.layoutParams as AppBarLayout.LayoutParams
        params.scrollFlags = 0
        val tradingRecordAdapter =
            TradingRecordAdapter(
                assetsBean.assetName!!
            )
        recyclerview.adapter = tradingRecordAdapter


        //充币
        recharge_tv.setOnClickListener {
            startActivity(Intent(this, RechargeActivity::class.java))
        }
        //提币
        withdraw_tv.setOnClickListener {
            if (IS_ACTIVATION == 1) {
                ToastUtils.show(this@CoinDetailActivity, getString(R.string.account_no_activation))
            } else {
                if (TextUtils.equals(assetsBean.assetName, "USDT")) {
                    startActivity(Intent(this, WithdrawActivity::class.java).putExtra("type", 2))
                } else if (TextUtils.equals(assetsBean.assetName, "GFT")) {
//                    ToastUtils.show("活动未开启")
                    startActivity(Intent(this, WithdrawActivity::class.java).putExtra("type", 3))
                }
            }
        }
        //转账
        transfer_tv.setOnClickListener {
            if (IS_ACTIVATION == 1) {
                ToastUtils.show(this@CoinDetailActivity, getString(R.string.account_no_activation))
            } else {
                if (assetsBean.assetBalance!! >= 0) {
                    TransferActivity.start(this, assetsBean)
                } else {
                    ToastUtils.show(this@CoinDetailActivity, "数据异常")
                }
            }
        }

        //GFC划转
        gfc_transfer.setOnClickListener {
            ToastUtils.show("活动未开启")
//            if (IS_ACTIVATION == 1) {
//                ToastUtils.show(this@CoinDetailActivity, getString(R.string.account_no_activation))
//            } else {
//                if (assetsBean.assetBalance!! >= 0) {
//                    GFCTransferActivity.start(this, assetsBean)
//                } else {
//                    ToastUtils.show(this@CoinDetailActivity, "数据异常")
//                }
//            }

        }

        copy_iv.setOnClickListener {
            //获取剪贴板管理器：
            val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val mClipData = ClipData.newPlainText("Label", block_chain_address_tv.text.toString())
            cm.setPrimaryClip(mClipData)
            showToast("复制成功")
        }
        record_nav_rb.setOnCheckedChangeListener { _, checkedId ->
            currentPage = 1
            isRefresh = true
            when (checkedId) {
                R.id.record_all_rb -> recordList("0")
                R.id.record_transfer_rb -> recordList("1")
                R.id.record_get_rb -> recordList("2")
            }
        }
        recordList("0")
        userViewModel.tradingRecordLiveData.observe(this, Observer {
            if (isRefresh) {
                refresh_layout.finishRefresh()
            } else {
                refresh_layout.finishLoadMore()
            }
            if (it.isEmpty()) {
                no_record_tv.visibility = View.VISIBLE
                tradingRecordAdapter.clearData()
                recyclerview.visibility = View.GONE
                params.scrollFlags = 0
            } else {
                if (it != null && it.isNotEmpty()) {
                    if (isRefresh) {
                        currentPage = 1
                    } else {
                        currentPage++
                    }
                }
                no_record_tv.visibility = View.GONE
                recyclerview.visibility = View.VISIBLE
                if (isRefresh) {
                    tradingRecordAdapter.refreshData(it)
                } else {
                    //TODO 接口还未做好分页 有重复数据 暂时先刷新
                    tradingRecordAdapter.refreshData(it)
                }
                params.scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or
                        AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED
            }
            appBarLayout.requestLayout()
        })

        userViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
            if (isRefresh) {
                refresh_layout.finishRefresh()
            } else {
                refresh_layout.finishLoadMore()
            }
        })
    }

    private fun recordList(events: String) {
        userViewModel.tradingRecord(assetsBean.assetGuid!!, events, 1, PAGE_SIZE)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onTransferEvent(e: TransferEvent) {
        val sumd = BigDecimal(assetsBean.assetBalance!!.toString()).subtract(BigDecimal(e.sum))

        assetsBean.assetBalance = sum.toDouble()
        balance_tv.text = "$" + sumd.toPlainString()
        rmb_tv.text = "=¥${sumd.multiply(BigDecimal(MONEY_SCALE.toString()))}"
        available.text =
            getString(R.string.available_detail) + PriceFormatUtil.format(
                assetsBean.assetBalance,
                4
            )
        frozen.text =
            getString(R.string.frozen_detail) + PriceFormatUtil.format(assetsBean.assetFrozen, 4)

        recordList("0")
    }

    private fun updateView() {
        for (bean in NetDataManager.assetsList) {
            if (TextUtils.equals(assetsBean.assetGuid, bean.assetGuid)) {
                when (assetsBean.assetGuid) {
                    "1" -> {
                        sum = PriceFormatUtil.format(
                            (bean.assetBalance!! + bean.assetFrozen!!) * 0.1 * MONEY_SCALE,
                            4
                        )
                    }
                    "2" -> {
                        sum = PriceFormatUtil.format(
                            (bean.assetBalance!! + bean.assetFrozen!!) * MONEY_SCALE,
                            4
                        )
                    }
                    "3", "4" -> {
                        sum = PriceFormatUtil.format(
                            (bean.assetBalance!! + bean.assetFrozen!!) * MONEY_UTIT_SCALE * MONEY_SCALE,
                            4
                        )
                    }
                }
                assetsBean = bean
                balance_tv?.text =
                    "$" + PriceFormatUtil.format(
                        (bean.assetBalance!! + bean.assetFrozen!!) * price,
                        4
                    )
                rmb_tv?.text = "=¥\t${sum}"

                available.text =
                    getString(R.string.available_detail) + PriceFormatUtil.format(
                        assetsBean.assetBalance,
                        4
                    )
                frozen.text = getString(R.string.frozen_detail) + PriceFormatUtil.format(
                    assetsBean.assetFrozen,
                    4
                )
                break
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAssetsEvent(e: AssetsEvent) {
        showProgress(false)
        updateView()
    }
}